#!/usr/bin/env python


import sys,time,commands,optparse

def options():
    usage='''Use like:
%s -u 2000 -d 5000
''' % __file__

    parser = optparse.OptionParser(usage)
    parser.add_option('-i','--interface',dest='Interface',type='str',default='all',help='Network interface')
    parser.add_option('-u','--upload',dest='Upwar',type='float',help='Upload speed')
    parser.add_option('-d','--download',dest='Downwar',type='float',help='Download speed')
    return parser

def main():
    parser = options()
    opt,args = parser.parse_args()
    if opt.Upwar and opt.Downwar:
        try:
            if opt.Interface == 'all':
                cmd = "sed -n '3,$p' /proc/net/dev|grep -v 'lo'|cut -d':' -f2|awk '{print $1,$9}'"
            else:
                cmd = "sed -n '3,$p' /proc/net/dev|grep '%s:'|cut -d':' -f2|awk '{print $1,$9}'" % opt.Interface
            out1 = commands.getoutput(cmd).strip()
            time.sleep(1)
            out2 = commands.getoutput(cmd).strip()
            
            if not out1:
                print 'Failed: No %s info.' % opt.Interface
                sys.exit(2)
            rx1 = tx1 = rx2 = tx2 = 0
            for result in out1.split('\n'):
                tmprx,tmptx = result.split()
                rx1 += int(tmprx)
                tx1 += int(tmptx)
            for result in out2.split('\n'):
                tmprx,tmptx = result.split()
                rx2 += int(tmprx)
                tx2 += int(tmptx)
            rx = (float(rx2) - float(rx1))/1024
            tx = (float(tx2) - float(tx1))/1024
            msg = 'Download speed:%.2fKB/s,Upload speed:%.2fKB/s|rx:%.0f:%.0f;tx:%.0f:%.0f' % (rx,tx,rx*1024,opt.Downwar*1024,tx*1024,opt.Upwar*1024)
            print msg

            if rx < opt.Downwar and tx < opt.Upwar:
                sys.exit(0)
            else:
                sys.exit(1)
            
        except Exception as err:
            print 'Failed: %s' % err
            sys.exit(2)
    else:
        print 'Failed: Missing param.'
        sys.exit(2)

if __name__=="__main__":
    main()
